package com.tanker.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;

import org.apache.http.client.HttpClient;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.client.RestTemplate;
/**
 * @author xqxue
 * @time 2018年1月17日 下午3:07:38
 */
@Service
public class BuyCpicService {

	@Autowired
	private CpicInsuranceConfig cpicInsuranceConfig;
	
	/**
	 * 发送请求
	 */
	public String sendPost(String xml) throws Exception{
		HttpClient httpClient = this.createSSLInsecureClient();
		int timeout = 60000;
		HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
		requestFactory.setReadTimeout(timeout);
		RestTemplate restTemplate = new RestTemplate(requestFactory);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);  
		LinkedMultiValueMap<String, String> param = new LinkedMultiValueMap<String,String>();
		param.add("messageRouter", cpicInsuranceConfig.getMessageRouter());
		param.add("tradingPartner", cpicInsuranceConfig.getPartnerCode());
		param.add("documentProtocol", cpicInsuranceConfig.getDocumentProtocol());
		param.add("requestMessage", xml);
		HttpEntity<LinkedMultiValueMap<String,String>> request = new HttpEntity<LinkedMultiValueMap<String,String>>(param,headers);
		String result= restTemplate.postForEntity(cpicInsuranceConfig.getTargetURL(), request, String.class).getBody();
		return result;
	}

	/**
	 * 获取ssl Httpclient对象
	 */
	private CloseableHttpClient createSSLInsecureClient()throws Exception {
		SSLContext sslContext = new SSLContextBuilder()
				.loadTrustMaterial(ResourceUtils.getFile(cpicInsuranceConfig.getCerPath()), cpicInsuranceConfig.getCerPassword().toCharArray(), new TrustStrategy() {
					//信任所有
					public boolean isTrusted(X509Certificate[] chain,
							String authType) throws CertificateException {
						return true;
					}}).build();
		SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
				sslContext);
		Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
				.register("http", PlainConnectionSocketFactory.getSocketFactory())
				.register("https", sslSocketFactory).build();
		PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

		return HttpClients.custom().setConnectionManager(connMgr).build();
	} 
	
	public static void main(String args[]) {
		try {
			File f = ResourceUtils.getFile("classpath:conf/cpickey/cpic_jttp.keystore");
			System.out.println(f.lastModified());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
